package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderDetailVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketService webSocketService;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
//        处理业务异常（购物车为空，没有选择地址）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        List<ShoppingCart> list = shoppingCartMapper.list(
                ShoppingCart.builder().
                        userId(BaseContext.getCurrentId()).
                        build());
        if (list.isEmpty()||list==null){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
//        插入订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
//        设置支付状态未支付
        orders.setPayStatus(Orders.UN_PAID);
//        设置订单状态待支付
        orders.setStatus(Orders.PENDING_PAYMENT);
//        用时间戳生成订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
//        设置电话号码
        orders.setPhone(addressBook.getPhone());
//        设置用户Id
        orders.setUserId(BaseContext.getCurrentId());

//        插入订单明细表
        orderMapper.insert(orders);
//        向订单明细表插入数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        list.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
//            关联订单Id
            orderDetail.setOrderId(orders.getId());

            orderDetails.add(orderDetail);
        });

        orderDetailMapper.insertBatch(orderDetails);

//        清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

//        封装VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

//        通过websocket推送消息
        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("orderId", ordersDB.getId().toString());
        map.put("content", "订单号：" + outTradeNo);

        String jsonString = JSON.toJSONString(map);
        webSocketService.sendMessage(jsonString);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> list = page.getResult();
        list.forEach(order -> {
            AddressBook addressBook = addressBookMapper.getById(order.getAddressBookId());
            order.setAddress(addressBook.getDetail());
            order.setConsignee(addressBook.getConsignee());
        });
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderDetailVO getOrderDetailById(Long id) {
        Orders orders=orderMapper.getById(id);
        List<OrderDetail> orderDetail=orderDetailMapper.getById(id);

        OrderDetailVO orderDetailVO=new OrderDetailVO();
        BeanUtils.copyProperties(orders,orderDetailVO);
        orderDetailVO.setOrderDetailList(orderDetail);

        return orderDetailVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    @Override
    public void cancel(Orders orders) {
        Orders orders1 = Orders.builder()
                .id(orders.getId())
                .status(Orders.CANCELLED)
                .cancelReason(orders.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders1);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = orderMapper.statistics();
        return orderStatisticsVO;
    }

    @Override
    public PageResult PageQuery(OrdersPageQueryDTO ordersPageQueryDTO) throws NoSuchFieldException, IllegalAccessException {
        PageResult pageResult = this.conditionSearch(ordersPageQueryDTO);
//        根据id查询订单详情
        List<OrderDetailVO> vo = new ArrayList<>();
//        将pageResult的数据列表赋值到vo
        pageResult.getRecords().forEach(record -> {
            OrderDetailVO orderDetailVO = new OrderDetailVO();
            BeanUtils.copyProperties(record, orderDetailVO);
            vo.add(orderDetailVO);
        });

//        反射获取id，根据id查询订单详情
        for (OrderDetailVO record : vo) {
            List<OrderDetail> detailList = orderDetailMapper.getById(record.getId());
            record.setOrderDetailList(detailList);
        }

        return new PageResult(pageResult.getTotal(),vo);
    }

    @Override
    public void reminder(Long id) {
        Orders orders=orderMapper.getById(id);
//        检查订单是否存在
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map<String,String> map=new HashMap<>();
        map.put("type","2");
        map.put("orderId",id.toString());
        map.put("content","订单号："+orders.getNumber());

        webSocketService.sendMessage(JSON.toJSONString(map));
    }
}
